package com.yanmaohu.nikita.scanner;

import com.yanmaohu.nikita.utility.ValueUtility;

import java.io.*;

/**
 * @author Bright Lee
 */
public final class SourceCode {

    private static final String FILE_ENCODING = ValueUtility.FILE_ENCODING;
    private static final int FILE_BUFFER_SIZE = ValueUtility.FILE_BUFFER_SIZE;

    private final File file;
    private final String content;

    public SourceCode(File file) {
        StringBuilder buffer = new StringBuilder(FILE_BUFFER_SIZE);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(file),
                            FILE_ENCODING),
                    FILE_BUFFER_SIZE);
            char[] cs = new char[FILE_BUFFER_SIZE];
            int count;
            while (true) {
                count = reader.read(cs);
                if (count <= 0) {
                    break;
                }
                buffer.append(cs, 0, count);
                if (count < FILE_BUFFER_SIZE) {
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        this.file = file;
        this.content = buffer.toString();
    }

    public File getFile() {
        return file;
    }

    public String getContent() {
        return content;
    }

    public int length() {
        return content.length();
    }

    public int charAt(int index) {
        return content.charAt(index);
    }

    public String substring(int beginIndex, int endIndex) {
        return content.substring(beginIndex, endIndex);
    }

}
